import {getToken, setToken, removeToken} from '@/utils/auth'
import {login, logout, getUserInfo} from '@/api/login'

const user = {
  state: {
    id: '',
    token:  getToken(),
    roles: [],
    message: '',
    code: undefined
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      if (roles === '1') {
        state.roles = ['common']
      } else if (roles === '0' ) {
        state.roles = ['admin']
      }
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_MESSAGE: (state, message) => {
      state.message = message
    },
    SET_CODE: (state, code) => {
      state.code = code
    }
  },

  actions: {
    Login({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.username, userInfo.password).then(response => {
          console.log("login-res:" + JSON.stringify(response.data))
          const data = response.data.data;
          commit('SET_CODE', response.data.code)
          if (response.data.code === 20000) {
            commit('SET_TOKEN', data.token)
            setToken(data.token)
          } else {
            commit('SET_MESSAGE', response.data.message)
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    GetUserInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          console.log("login-response:" + JSON.stringify(response.data))
          const data = response.data.data;
          if (response.data.code === 20000) {
            if (data) {
              commit('SET_ROLES', data.role)
              commit('SET_ID', data.id)
            } else {
              reject('获取用户信息失败')
            }
          } else {
            commit('SET_MESSAGE', response.data.message)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    Logout ({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    FrontLogout({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user


